<template>
  <div class="category-container">
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="form-inline">
        <el-form-item label="分类名称">
          <el-input v-model="filterForm.name" placeholder="请输入分类名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="分类类型">
          <el-select v-model="filterForm.type" placeholder="请选择" clearable>
            <el-option label="菜品分类" :value="1"></el-option>
            <el-option label="套餐分类" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="operation-container" v-if="username === '管理员'">
      <el-button type="primary" @click="handleAdd">新增分类</el-button>
    </div>
    
    <el-table
      :data="categoryList"
      border
      style="width: 100%"
      v-loading="loading">
      <el-table-column
        type="index"
        label="序号"
        width="60">
      </el-table-column>
      <el-table-column
        prop="name"
        label="分类名称"
        width="150">
      </el-table-column>
      <el-table-column
        prop="type"
        label="分类类型"
        width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type === 1 ? 'success' : 'primary'">
            {{ scope.row.type === 1 ? '菜品分类' : '套餐分类' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="sort"
        label="排序"
        width="60">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="80">
        <template slot-scope="scope">
          <el-switch
          v-if="username === '管理员'"
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)">
          </el-switch>
          <el-tag
            v-else
            :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="160">
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="160">
      </el-table-column>
      <el-table-column
        label="操作"
        width="150">
        <template slot-scope="scope">
          <el-button
          v-if="username === '管理员'"
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
          v-if="username === '管理员'"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    
    <!-- 新增/编辑分类对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="categoryForm" :rules="rules" ref="categoryForm" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="分类类型" prop="type">
          <el-radio-group v-model="categoryForm.type">
            <el-radio :label="1">菜品分类</el-radio>
            <el-radio :label="2">套餐分类</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="1" :max="99"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCategoryPage,
  addCategory,
  updateCategory,
  deleteCategory,
  updateCategoryStatus
  // getCategoryList - 暂未使用，需要时再导入
} from '@/api/category'

export default {
  name: 'CategoryManagement',
  data() {
    return {
      // 用户名
      username: '',
      // 分类列表数据
      categoryList: [],
      // 加载状态
      loading: false,
      // 分页信息
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 筛选条件
      filterForm: {
        name: '',
        type: ''
      },
      // 对话框状态
      dialogVisible: false,
      dialogTitle: '新增分类',
      // 表单数据
      categoryForm: {
        id: null,
        name: '',
        type: 1,
        sort: 1
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择分类类型', trigger: 'change' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 组件创建时加载数据
    this.fetchData()

     // 从本地存储获取用户信息
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      const user = JSON.parse(userInfo)
      this.username = user.name || '管理员'
    }
  },
  methods: {
    // 获取分类数据
    fetchData() {
      this.loading = true
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize,
      }

      if (this.filterForm.name) {
        params.name = this.filterForm.name
      }

      // 处理分类类型
      if (this.filterForm.type) {
        params.type = this.filterForm.type
      }
      
      getCategoryPage(params)
        .then(res => {
          if (res.code === 1) {
            this.categoryList = res.data.records
            this.total = res.data.total
          } else {
            this.$message.error(res.msg || '获取分类列表失败')
          }
        })
        .catch(err => {
          console.error('获取分类列表失败', err)
          this.$message.error('获取分类列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 查询
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    
    // 重置查询表单
    resetForm() {
      this.filterForm = {
        name: '',
        type: ''
      }
      this.handleSearch()
    },
    
    // 新增分类
    handleAdd() {
      this.dialogTitle = '新增分类'
      this.categoryForm = {
        id: null,
        name: '',
        type: 1,
        sort: 1
      }
      this.dialogVisible = true
      // 在下一个事件循环中重置表单验证
      this.$nextTick(() => {
        if (this.$refs.categoryForm) {
          this.$refs.categoryForm.resetFields()
        }
      })
    },
    
    // 编辑分类
    handleEdit(row) {
      this.dialogTitle = '编辑分类'
      this.categoryForm = {
        id: row.id,
        name: row.name,
        type: row.type,
        sort: row.sort
      }
      this.dialogVisible = true
    },
    
    // 状态变更
    handleStatusChange(row) {
      const status = row.status
      const statusText = status === 1 ? '启用' : '禁用'
      
      this.loading = true
      updateCategoryStatus(row.id, status)
        .then(res => {
          if (res.code === 1) {
            this.$message.success(`分类「${row.name}」已${statusText}`)
          } else {
            // 恢复原状态
            row.status = status === 1 ? 0 : 1
            this.$message.error(res.msg || `${statusText}失败`)
          }
        })
        .catch(err => {
          // 恢复原状态
          row.status = status === 1 ? 0 : 1
          console.error(`${statusText}分类失败`, err)
          this.$message.error(`${statusText}分类失败`)
        })
        .finally(() => {
          this.loading = false
          // 刷新列表
          this.fetchData()
        })
    },
    // 删除分类
    handleDelete(row) {
      this.$confirm('确认删除该分类?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除分类API
        this.loading = true
        deleteCategory(row.id)
          .then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功')
              // 刷新列表
              this.fetchData()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          })
          .catch(err => {
            console.error('删除分类失败', err)
            this.$message.error('删除分类失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 提交表单
    submitForm() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          this.loading = true
          
          if (this.categoryForm.id) {
            // 编辑分类
            updateCategory(this.categoryForm)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success('编辑成功')
                  this.dialogVisible = false
                  // 刷新列表
                  this.fetchData()
                } else {
                  this.$message.error(res.msg || '编辑失败')
                }
              })
              .catch(err => {
                console.error('编辑分类失败', err)
                this.$message.error('编辑分类失败')
              })
              .finally(() => {
                this.loading = false
              })
          } else {
            // 新增分类
            addCategory(this.categoryForm)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success('新增成功')
                  this.dialogVisible = false
                  // 刷新列表
                  this.fetchData()
                } else {
                  this.$message.error(res.msg || '新增失败')
                }
              })
              .catch(err => {
                console.error('新增分类失败', err)
                this.$message.error('新增分类失败')
              })
              .finally(() => {
                this.loading = false
              })
          }
        }
      })
    },
    // 页码改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1 // 切换每页条数时重置为第一页
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>